package com.test.java;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Base64;

//文件与base64字符相互转换的工具类
public class Base64TransformTool {

    public static void main(String[] args) throws IOException {
       String base64="UEsDBBQACAgIANcOplQAAAAAAAAAAAAAAAAkAAAAMjAyMjA1MDYwMTU0NDdfNjA3NDcwNzEzNjUwNTQ0NjQudHh0lVvhmuwqCvydfZeTT1AQ3//FthDTHW0zm+37Y06Gvk2rUFQhk3PCi1So5pJqriwpcSpSNFc58mxmJjyyZpNs2dxcGl5pvHIispSp1AP/z+m/OlL8+D7/5/ahTE3V/BE+U234uGMxC/vnwycnfAHa+cytZtZysNTJ5/f57rM0KbV/ACchyviEYzFj7ew+i2rGpvz49Pfmit1qB5/+VvzI9HU8+aNC+HbwA38Zi2l18udmIuprxObjHdt95SxcrB00XNhY4sZhsmYs7CtIjAMtrR6LGcdU3CFp4pZ4u0AYKusrh60Wy62EQ7wkH4u5pqrdoRVKFg65fB1SeGTmNw5Lxiey9rBBvHrIHYtZJHWHRfAe+w2bfoS5FLWjmJ1yO71i6fQPX0IVy8KOUA9V7NuSHm6uWvqu5lwN+xuLpGmRhl2laofSKXjvoSfJQ9yUTMYpFllMqc7H6OYk0h2WIrmo/LVI/uThlCJzpJo1cgDwSG1cAAPHbPbQ6ZmBOGardRepJSliNR90HeTlmXY+kxXPbLmClQJWbmZsQU09dhDTLe8RwJit2Cd26h+LRI6psfVF+v7NkONmahyLFNUqv+nYj9IQ8fVdsGqhJhznaNi1fCxm/J5GsMKV/ok3L84xAcLw/3fEwbbgSNqcj4JkbX2JiCoi/T1Hfy8MKZWPx7FE2q2RkLhA246pmeBd501F4aiqPSGZ8HV4CzkJUES5vNlU7JtkqrU7rMpcp7CBudSiNUK1AuV/N9XDhnGICNXPppb4qTuPWYpYGzAuisUes5np8ojcpDD/lkdAYWrrpm4DFd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Xt/K1fTBB0ZLuf438BUEsHCOatdtgwDwAAYzcAAFBLAQIUABQACAgIANcOplTmrXbYMA8AAGM3AAAkAAAAAAAAAAAAAAAAAAAAAAAyMDIyMDUwNjAxNTQ0N182MDc0NzA3MTM2NTA1NDQ2NC50eHRQSwUGAAAAAAEAAQBSAAAAgg8AAAAA";
         String url="G:/data";
        String end="123.zip";
        getFileByBytes(base64.getBytes(),url,end);
    }

    private static void getFileByBytes(byte[] bytes, String filePath, String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        try {
            File dir = new File(filePath);
            if (!dir.exists()) {// 判断文件目录是否存在
                dir.mkdirs();
            }
            File file = new File(filePath + File.separator + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
        } catch (IOException e) {
//            LOG.info("exception:{}", e.getMessage());
        } finally {
            if (null != bos) {
                try {
                    bos.close();
                } catch (IOException e) {
//                    LOG.info("exception:{}", e.getMessage());
                }
            }
            if (null != fos) {
                try {
                    fos.close();
                } catch (IOException e) {
//                    LOG.info("exception:{}", e.getMessage());
                }
            }
        }
    }
    /**
     * 将文件转换为base64字符串，并写入txt文本文件（由于base64字符可能会很长）
     * 返回保存base64字符串的路径
     *
     * @param filePath      需要转换的文件的路径
     * @param base64FileDir 保存base64字符串的路径，默认当前路径
     * @return 返回保存base64字符串的路径
     */
    public static String fileToBase64Str(String filePath, String base64FileDir) throws IOException {
        checkParamNotNull(filePath);
        Path path = Paths.get(filePath);
        byte[] fileBytes = Files.readAllBytes(path);
        byte[] base64Byte = Base64.getEncoder().encode(fileBytes);
        String fileName = path.getFileName().toString();
        String base64FileName = fileName.substring(0, fileName.lastIndexOf(".")) + ".txt";
        Files.write(Paths.get(path.getParent().toString(), base64FileName), base64Byte);
        return path.getParent().toString() + File.separator + base64FileName;
    }

    /**
     * 将base64字符串还原成文件
     * 返回文件路径
     * @param base64FilePath base64字符串的文件路径
     * @param filePath       还原的文件路径，默认当前ase64字符串的文件路径
     * @param suffix         文件后缀名
     * @return 返回文件路径
     */
    public static String base64ToFile(String base64FilePath, String filePath, String suffix) throws IOException {
        checkParamNotNull(base64FilePath,suffix);
        if(filePath == null){
            filePath = base64FilePath.substring(0,base64FilePath.lastIndexOf(".")+1)
                    + suffix;
        }
        byte[] base64Byte = Files.readAllBytes(Paths.get(base64FilePath));
        try {
            Files.write(Paths.get(filePath), Base64.getDecoder().decode(base64Byte), StandardOpenOption.CREATE);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return filePath;
    }
    private static void checkParamNotNull(Object param,Object... others){
        if(param == null){
            throw new IllegalArgumentException("参数不能为空");
        }
        if(param instanceof String){
            if(((String) param).length() == 0){
                throw new IllegalArgumentException("参数不能为空");
            }
        }
        if(others!=null){
            Object[] params = others;
            for (Object o : params) {
                checkParamNotNull(o);
            }
        }
    }
}
